from random import randint

from django import http
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection

from libs.yuntongxun.sms import CCP


class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):

        text, image = captcha.generate_captcha()
        redis_coon = get_redis_connection('code')
        redis_coon.setex('img_%s' % uuid, 240, text)

        return http.HttpResponse(image, content_type='image/jpeg')
import logging
logger = logging.getLogger('django')
class SmsCodeView(View):

    def get(self, request, mobile):
        param = request.GET
        uuid = param.get('image_code_id')#图片验证吗的uuid
        text_client = param.get('image_code')#客户输入的验证码

        #链接数据库redis
        redis_conn = get_redis_connection('code')
        text_server = redis_conn.get('img_%s' %uuid)
        if text_server is None:
            return http.HttpResponseBadRequest('图片验证码已过期')

        try:
            redis_conn.delete('img_%s'%uuid)

        except Exception as e:
            logger.error(e)
        if text_server.decode().lower() != text_client.lower():
            return http.HttpResponseBadRequest('图片验证码有误')
        sms_code = '%06d'%(randint(0,999999))#生成随机验证码
        redis_conn.setex('sms_%s'%mobile,240,sms_code)#存储随机的验证码

        CCP().send_template_sms(mobile,[sms_code,4],1)

        return JsonResponse({'code':200})









